package com.lovezy.platform.filestore.service;

import com.lovezy.platform.core.base.AppServer;
import com.lovezy.platform.filestore.exception.FileStoreException;
import com.lovezy.platform.filestore.exception.FileStoreExceptionEnum;
import com.lovezy.platform.filestore.model.File;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

import static com.lovezy.platform.filestore.exception.FileStoreExceptionEnum.FILE_STORE_ERROR;

/**
 * 文件帮助类
 * Created by jin on 2017/11/6.
 */
public final class LocalFileHelper implements FileHelper{

    private final Log log = LogFactory.getLog(LocalFileHelper.class);

    @Autowired
    private AppServer appServer;

    @Nullable
    @Override
    public String toDownloadUrl(File file) {
        return toDownloadUrl(file.getUrl());
    }

    @Override
    public String toDownloadUrl(String url) {
        if (!StringUtils.hasText(url)) {
            return null;
        }
        return appServer.getDownloadPath() + url;
    }

    @NotNull
    private String toPhysicalPath(@NotNull File file) {
        String savePath = appServer.getFileSavePath();
        return savePath == null ? java.io.File.separator : savePath + file.getDir() + java.io.File.separator + file.getUrl();
    }
    @NotNull @Override
    public byte[] getFileByteArray(File dbFile) {
        String path = toPhysicalPath(dbFile);
        java.io.File f = new java.io.File(path);
        if (!f.exists() || f.isDirectory()) {
            throw new FileStoreException(FileStoreExceptionEnum.FILE_MISSING);
        }
        try {
            return Files.readAllBytes(Paths.get(path));
        } catch (IOException e) {
            log.error("读取文件失败", e);
            throw new FileStoreException(FileStoreExceptionEnum.READ_FILE_ERROR);
        }
    }

    @Override
    public void storeFile(InputStream inputStream,File fileData) {
        java.io.File file = new java.io.File(appServer.getFileSavePath() + fileData.getDir()+java.io.File.separator + fileData.getUrl());
        try {
            OutputStream outputStream = new FileOutputStream(file);
            IOUtils.copy(inputStream,outputStream);
        } catch (IOException e) {
            log.error("保存文件出错", e);
            throw new FileStoreException(FILE_STORE_ERROR);
        }
    }
}
